package com.dc.business.datacollectbusiness.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dc.business.datacollectbusiness.controller.publicInstitutionController;
import com.dc.business.datacollectbusiness.mapper.publicInstitutionMapper;
import com.dc.business.datacollectbusiness.model.buildColletModel;
import com.dc.business.datacollectbusiness.model.tbengPushCustomData;
import com.dc.business.datacollectbusiness.service.publicInstitutionService;
import com.dc.business.datacollectbusiness.utils.AESUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Properties;

@Service
@Slf4j
public class publicInstitutionServiceImpl implements publicInstitutionService {

    @Autowired
    private publicInstitutionMapper institutionMapper;

    @Autowired
    private RestTemplate restTemplate;

    String ip = "106.116.244.199";
    String port = "8089";
    // 身份认证接口url
    String identityFunc = "/real/identity";
    // 数据传输存储url
    String sendDataToStorageFunc = "/real/recForm";


    // 远端调用身份认证接口
    public JSONObject identityTest(buildColletModel buildColletModel) throws Exception {
        Long buildPublicId = buildColletModel.getBuildPublicId();
        String buildSingleId = buildColletModel.getBuildSingleId();
        Long colletId = buildColletModel.getCollectId();
        String upType = buildColletModel.getUpType();

        // 构造远端身份认证接口完整请求url
        String url = "http://" + ip + ":" + port + identityFunc;

        // 构造请求json报文格式
        JSONObject requestJSON = new JSONObject();
        requestJSON.put("buildPublicId", buildPublicId);
        requestJSON.put("buildSingleId", buildSingleId);
        requestJSON.put("colletId", colletId);
        requestJSON.put("upType", upType);

        // 请求参数json报文进行AES算法加密
        String encryptData = AESUtil.encrypt(requestJSON.toString());

        // 构造远端身份认证结构请求json报文
        JSONObject data = new JSONObject();
        data.put("data", encryptData);

        // 远端调用
        JSONObject responseJson = restTemplate.postForObject(url, data, JSONObject.class);
        Object responseValue = responseJson.get("result");
        String result = AESUtil.decrypt(responseValue.toString());

        // 返回调用远端接口json报文
        return JSONObject.parseObject(result);
    }

    public String sendDataToStorageGo(buildColletModel buildColletModel) throws Exception {

        Long buildPublicId = buildColletModel.getBuildPublicId();
        String buildSingleId = buildColletModel.getBuildSingleId();
        Long colletId = buildColletModel.getCollectId();
        String upType = buildColletModel.getUpType();
        String code = buildColletModel.getCode();
        Double energy = buildColletModel.getEnergy();
        String type = buildColletModel.getType();
        Double multiple = buildColletModel.getMultiple();

        String passCode;
        // 判断远端身份识别是否通过
        passCode = this.identityTest(buildColletModel).get("code").toString();
        if (passCode.equals("500")) {
            return "身份识别不通过,请检查后重新输入再试......";
        } else if (passCode.equals("200")) {
            // 判断是否有采集器
            if (upType.equals("1")) {  // 有采集器
                log.info("身份识别通过,本次请求有采集器......");

                // 构造请求json报文
                JSONObject requestJSON1 = new JSONObject();
                requestJSON1.put("buildPublicId", buildPublicId);
                requestJSON1.put("buildSingleId", buildSingleId);
                requestJSON1.put("colletId", colletId);
                requestJSON1.put("upType", upType);
                JSONArray requestData1 = new JSONArray();
                JSONObject objec1 = new JSONObject();
                JSONObject objec2 = new JSONObject();

                // 拿取该设备对应各数值
                tbengPushCustomData tbengPushCustomDataA = institutionMapper.findLatestByTfCollecterProductCodeA(String.valueOf(colletId));
                tbengPushCustomData tbengPushCustomDataB = institutionMapper.findLatestByTfCollecterProductCodeB(String.valueOf(colletId));

                log.info("拿取该设备对应各数值: " + tbengPushCustomDataA);
                log.info("拿取该设备对应各数值: " + tbengPushCustomDataB);
                Double pvA = Double.valueOf(tbengPushCustomDataA.getPv());
                pvA *= multiple;
                String tfSensorProductCodeA = tbengPushCustomDataA.getTfSensorProductCode();
                objec1.put("t13a",pvA);
                objec1.put("meterid",tfSensorProductCodeA);
                objec1.put("time",tbengPushCustomDataA.getUploadTime());
                requestData1.add(objec1);


                Double pvB = Double.valueOf(tbengPushCustomDataB.getPv());
                pvB *= multiple;
                String tfSensorProductCodeB = tbengPushCustomDataB.getTfSensorProductCode();
                objec2.put("t13a",pvB);
                objec2.put("meterid",tfSensorProductCodeB);
                objec2.put("time",tbengPushCustomDataB.getUploadTime());
                requestData1.add(objec2);

                requestJSON1.put("data", requestData1);

                // AES算法加密请求json报文
                String encryptData = AESUtil.encrypt(requestJSON1.toString());
                // 构造远端身份认证结构请求json报文
                JSONObject data = new JSONObject();
                data.put("data", encryptData);

                // 请求远端数据传输存储接口
                String url = "http://" + ip + ":" + port + sendDataToStorageFunc;
                JSONObject reponseJson = restTemplate.postForObject(url, data, JSONObject.class);
                Object responseValue = reponseJson.get("result");

                // 解码AES算法得到的数据
                String decryptData = AESUtil.decrypt(responseValue.toString());

                JSONObject resultJson = JSONObject.parseObject(decryptData);
                if (resultJson.get("code").toString().equals("200")) {
                    return "本次有采集器,验证成功......";
                } else if (resultJson.get("code").toString().equals("500")) {
                    return "本次有采集器,验证失败......";
                } else if (resultJson.get("code").toString().equals("10001 ")) {
                    return "本次有采集器,单体建筑ID错误......";
                } else if (resultJson.get("code").toString().equals("10002 ")) {
                    return "本次有采集器,采集器ID错误......";
                } else if (resultJson.get("code").toString().equals("10003 ")) {
                    return "本次有采集器,表具ID错误......";
                }
            } else if (upType.equals("2")){  // 无采集器
                log.info("身份识别通过,本次请求无采集器......");
                // 构造请求json报文
                JSONObject requestJSON2 = new JSONObject();
                requestJSON2.put("upType", upType);
                JSONArray requestData2 = new JSONArray();
                JSONObject objec2 = new JSONObject();
                objec2.put("code",code);
                objec2.put("energy",energy);
                objec2.put("type",type);
                requestData2.add(objec2);
                requestJSON2.put("data", requestData2);
                String encryptData = AESUtil.encrypt(requestJSON2.toString());

                // 构造远端身份认证结构请求json报文
                JSONObject data = new JSONObject();
                data.put("data", encryptData);

                // 请求远端数据传输存储接口
                String url = "http://" + ip + ":" + port + sendDataToStorageFunc;
                JSONObject reponseJson = restTemplate.postForObject(url, data, JSONObject.class);
                Object responseValue = reponseJson.get("result");

                // 解码AES算法得到的数据
                String decryptData = AESUtil.decrypt(responseValue.toString());

                JSONObject resultJson = JSONObject.parseObject(decryptData);
                if (resultJson.get("code").toString().equals("200")) {
                    return "本次无采集器,验证成功......";
                } else if (resultJson.get("code").toString().equals("500")) {
                    return "本次无采集器,验证失败......";
                } else if (resultJson.get("code").toString().equals("10001 ")) {
                    return "本次无采集器,单体建筑ID错误......";
                } else if (resultJson.get("code").toString().equals("10002 ")) {
                    return "本次无采集器,采集器ID错误......";
                } else if (resultJson.get("code").toString().equals("10003 ")) {
                    return "本次无采集器,表具ID错误......";
                }
            } else {
                return "upType: 1,2[请勿填写其他参数]";
            }
        }
        return "远端调用数据存储传输接口失败....";
    }

    public HashMap<Long,String> sendDataToStorageMap() throws IOException {
        // 从配置文件拿取所有设备信息并实例化对象
        String fileName = "EnergyEfficientSystem.properties";
        Properties props = new Properties();
        InputStream is = publicInstitutionController.class.getClassLoader().getResourceAsStream(fileName);
        props.load(is);
        String buildPublicId = (String) props.get("EnergyEfficientSystem.buildPublicId");
        String[] buildPublicIdList = buildPublicId.split(",");

        String buildSingleId = (String) props.get("EnergyEfficientSystem.buildSingleId");
        String[] buildSingleIdList = buildSingleId.split(",");

        String collectId = (String) props.get("EnergyEfficientSystem.collectId");
        String[] collectIdList = collectId.split(",");


        String upType = (String) props.get("EnergyEfficientSystem.upType");
        String[] upTypeList = upType.split(",");

        String code = (String) props.get("EnergyEfficientSystem.code");
        String[] codeList = code.split(",");

        String energy = (String) props.get("EnergyEfficientSystem.energy");
        String[] energyList = energy.split(",");

        String type = (String) props.get("EnergyEfficientSystem.type");
        String[] typeList = type.split(",");

        String multiple = (String) props.get("EnergyEfficientSystem.multiple");
        String[] multipleList = multiple.split(",");

        HashMap<Long, String> resultMap = new HashMap<>();
        for (int i = 0; i < buildPublicIdList.length; i++) {
            buildColletModel buildColletModel = new buildColletModel();
            buildColletModel.setBuildPublicId(Long.valueOf(buildPublicIdList[i]));
            buildColletModel.setBuildSingleId(buildSingleIdList[i]);
            buildColletModel.setCollectId(Long.valueOf(collectIdList[i]));
            buildColletModel.setUpType(upTypeList[i]);
            buildColletModel.setCollectId(Long.valueOf(collectIdList[i]));
            buildColletModel.setCode(codeList[i]);
            buildColletModel.setEnergy(Double.valueOf(energyList[i]));
            buildColletModel.setType(typeList[i]);
            buildColletModel.setMultiple(Double.valueOf(multipleList[i]));
            String resultString = null;
            try {
                resultString = this.sendDataToStorageGo(buildColletModel);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            resultMap.put(buildColletModel.getCollectId(), resultString);
        }
        return resultMap;
    }

}
